/* eslint-disable react/jsx-handler-names */
/* eslint-disable eqeqeq */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tree, Input, message, Form, Select } from 'antd';
import styles from './styles.less';
import { connect } from 'dva';
import directConfig from '../business/tradingDirect/config';
import { PrimaryC } from '@/src/components';

const { TreeNode } = Tree;
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 7, offset: 0 },
    xxl: { span: 7, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 15, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};
const { TextArea } = Input;
class SequenceFlowPannel extends Component {
  // 默认值
  static defaultProps = {
    id: undefined, // 节点ID
    name: undefined, // 节点名称
    condition: undefined, // 条件
    nameChanged: () => {}, // 名字变更事件
    conditionChanged: () => {}, // 条件变更事件
    saveFlow: () => {}, // 保存设置事件
    mode: 'view', // 默认查看模式
    xmlDoc: undefined, // 流程图XML对象
  };

  state = {
    currentCondition: undefined, // 当前条件选择的时 同意 驳回 还是判断
  };

  formRef = React.createRef();

  componentDidMount() {
    this.formRef.current.setFieldsValue({
      id: this.props.id, // 节点ID
      name: this.props.name, // 节点名称
      condition: this.props.condition, // 节点对应条件
    });
    setTimeout(() => {
      this.setState(
        {
          // 当前条件
          currentCondition: this.props.condition,
        },
        () => {
          if (this.state.currentCondition != 3) return;
          setTimeout(() => {
            this.queryRemarkExpression(this.props.id, this.props.expression); // 查询备注信息 并取公式
          }, 500);
        },
      );
    }, 0);
  }

  componentDidUpdate(preProps) {
    if (this.props.id !== preProps.id) {
      this.formRef.current.setFieldsValue({ id: this.props.id });
      if (this.props.expression) this.queryRemarkExpression(this.props.id, this.props.expression); // 查询备注信息 并取公式
    }
    if (this.props.name !== preProps.name) {
      this.formRef.current.setFieldsValue({ name: this.props.name });
    }
    if (this.props.condition !== preProps.condition) {
      this.formRef.current.setFieldsValue({ condition: this.props.condition });
      this.setState({
        // 当前条件
        currentCondition: this.props.condition,
      });
    }
  }

  // 查询备注信息
  queryRemarkExpression = (id, expression) => {
    console.log(id, '查询id');
    if (expression)
      this.props.dispatch({
        type: 'bpmnM/getBpmnRemarkInfo',
        payload: {
          sequenceId: id,
          flowType: this.props.flowType,
          flowChildType: this.props.flowChildType,
        },
        callback: (data) => {
          if (data == 'fail') {
            message.error('备注信息查询失败！');
            this.formRef.current.setFieldsValue({ remark: undefined });
          } else {
            this.formRef.current.setFieldsValue({ remark: data || undefined });
          }
          const str = expression?.body || '';
          this.formRef.current.setFieldsValue({ conditionExpression: str.substring(str.lastIndexOf('${') + 2, str.indexOf("=='true'") - 3) });
        },
      });
  };

  // 保存备注信息
  saveRemark = (id) => {
    if (this.state.currentCondition != 3) return;
    console.log(id, '保存id');
    this.props.dispatch({
      type: 'bpmnM/saveBpmnRemarkInfo',
      payload: {
        sequenceId: id,
        description: this.formRef.current.getFieldValue('remark'),
        flowType: this.props.flowType,
        flowChildType: this.props.flowChildType,
      },
      callback: (data) => {
        if (!data) message.error('备注信息保存失败！');
      },
    });
  };

  // 点击保存设置
  handleSubmit = async () => {
    const values = await this.formRef.current.validateFields();
    if (values) {
      // 抛出保存设置事件
      this.props.saveFlow(values);
      this.saveRemark(this.props.id); // 保存备注信息
    }
  };

  // 条件下拉框变化
  conditionChanged = (e) => {
    const { form, conditionChanged, mode } = this.props;
    this.setState({
      currentCondition: e,
    });
    conditionChanged(e);
  };

  renderDict() {
    const {
      globalM: {
        dataDictionary: { CREDITBND_MONITOR_BONDTYPEI = [] },
      },
    } = this.props;
    const loop = (data) =>
      data.map((item) => {
        if (item.children && item.children.length) {
          return (
            <TreeNode key={item.code} title={`${item.code} — ${item.value}`}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.code} title={`${item.code} — ${item.value}`} />;
      });
    return (
      <Tree defaultExpandAll={true} autoExpandParent={true} blockNode={true}>
        {loop(CREDITBND_MONITOR_BONDTYPEI)}
      </Tree>
    );
  }

  render() {
    const { mode } = this.props;
    let tradeList = [];
    directConfig.map((item) => {
      if (item.value == 7) {
        tradeList = item.tradingDirect;
      }
    });
    return (
      <div className={`${styles.SequenceFlowPannel}`}>
        <div>条件设置</div>
        <Form onFinish={this.handleSubmit} ref={this.formRef}>
          <Form.Item label='编号' name={'id'} className={'formCls1 '}>
            <Input disabled={true} />
          </Form.Item>
          <Form.Item label='名称' name={'name'} rules={[{ required: true, message: '名称不能为空!' }]} {...FormItemLayout} className={'formCls1'}>
            <Input disabled={mode === 'view'} onChange={this.nameChanged} />
          </Form.Item>
          <Form.Item label='条件' name={'condition'} rules={[{ required: true, message: '条件不能为空!' }]} {...FormItemLayout} className={'formCls1'}>
            <Select getPopupContainer={(triggerNode) => triggerNode.parentNode} onChange={this.conditionChanged} disabled={mode === 'view'}>
              <Select.Option value='1'>同意</Select.Option>
              <Select.Option value='2'>驳回</Select.Option>
              {this.props.isOrder && <Select.Option value='3'>判断</Select.Option>}
            </Select>
          </Form.Item>
          {this.state.currentCondition == 3 && (
            <div>
              <div className='conditionExpression'>
                <p>关系规则</p>
                <Form.Item name='conditionExpression' rules={[{ required: true, message: '关系规则不能为空!' }]}>
                  <TextArea readOnly={mode === 'view'} placeholder='请输入关系规则公式' />
                </Form.Item>
              </div>
              <div className='conditionExpression'>
                <p>备注</p>
                <Form.Item name='remark' rules={[{ required: true, message: '备注不能为空!' }]}>
                  <TextArea readOnly={mode === 'view'} placeholder='请输入备注信息' />
                </Form.Item>
              </div>
              <div className='conditionExpression'>
                <p>公式说明</p>
                <div className='conditionExpressionInfo'>
                  <ul>
                    <li>
                      <p>tradeType — 交易类型</p>
                      <ul>
                        {tradeList &&
                          tradeList.map((item, i) => {
                            return <li key={i}>{`${item.value} — ${item.title}`}</li>;
                          })}
                      </ul>
                    </li>
                    <li>
                      <p>amt — 金额</p>
                    </li>
                    <li>
                      <p>day — 天数</p>
                    </li>
                    <li>
                      <p>rate — |回购利率-质押券的市场利率|*100</p>
                    </li>
                  </ul>
                  <ul>
                    <li>
                      <p>busType — 业务种类</p>
                    </li>
                    <div className='treeCls'>{this.renderDict()}</div>
                  </ul>
                </div>
              </div>
            </div>
          )}

          {mode === 'view' ? null : (
            <Form.Item className={'saveClass'}>
              <PrimaryC title='保存设置' htmlType='submit' />
            </Form.Item>
          )}
        </Form>
      </div>
    );
  }
}
// props默认值
SequenceFlowPannel.propsTypes = {
  id: PropTypes.string, // 节点ID
  name: PropTypes.string, // 节点名称
  condition: PropTypes.string, // 条件
  nameChanged: PropTypes.func, // 名字变更事件
  conditionChanged: PropTypes.func, // 条件变更事件
  mode: PropTypes.string, // 模式（view-不可编辑，editor-可编辑）
  xmlDoc: PropTypes.object, // 流程图XML对象
  saveFlow: PropTypes.func, // 保存设置事件
  isOrder: PropTypes.bool, // 回购指令
};

export default connect(({ bpmnM, globalM }) => ({ bpmnM, globalM }))(SequenceFlowPannel);
